package com.dz.risk.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dz.risk.common.SysConstant;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.common.utils.ResponseUtils;
import com.dz.risk.dao.BondRiskInformationSheetDao;
import com.dz.risk.pojo.QueryParams;
import com.dz.risk.pojo.domain.*;
import com.dz.risk.service.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service("bondRiskInformationSheetService")
public class BondRiskInformationSheetServiceImpl extends ServiceImpl<BondRiskInformationSheetDao, BondRiskInformationSheetEntity> implements BondRiskInformationSheetService {
    @Autowired
    private BondRiskInformationSheetDao bondRiskInformationSheetDao;
    @Autowired
    private EarlyWarningDebtListService earlyWarningDebtListService;
    @Autowired
    private ProprietaryHoldingBondInformationService proprietaryHoldingBondInformationService;
    @Autowired
    private ProprietaryValuationOfBondHoldingsInformationService proprietaryValuationOfBondHoldingsInformationService;
    @Autowired
    private ConfigService configService;

    @Override
    public IPage<BondRiskInformationSheetEntity> query(QueryParams queryParams) {
        IPage<BondRiskInformationSheetEntity> page = new Page<>();
        page.setCurrent(queryParams.getPageNum());
        page.setSize(queryParams.getPageSize());
        QueryWrapper<BondRiskInformationSheetEntity> wrapper = new QueryWrapper<BondRiskInformationSheetEntity>();

        wrapper.lambda().eq(!StringUtils.isEmpty(queryParams.getVersion()),BondRiskInformationSheetEntity::getVersion, queryParams.getVersion()).orderByDesc(BondRiskInformationSheetEntity::getVersion);
        IPage<BondRiskInformationSheetEntity> entityIPage = bondRiskInformationSheetDao.selectPage(page, wrapper);
        return entityIPage;
    }

    @Override
    public void roll(Long version) throws RRException {

        //预警债券名单
        List<EarlyWarningDebtListEntity> earlyWarningDebtListEntityList =  earlyWarningDebtListService.queryByVersion(version);
        //自营持有债券信息
        List<ProprietaryHoldingBondInformationEntity> proprietaryHoldingBondInformationEntityList = proprietaryHoldingBondInformationService.queryByVersion(version);
        //自营估值债券持仓
        List<ProprietaryValuationOfBondHoldingsInformationEntity> proprietaryValuationOfBondHoldingsInformationEntityList = proprietaryValuationOfBondHoldingsInformationService.queryByVersion(version);

        List<BondRiskInformationSheetEntity> bondRiskInformationSheetEntities=new ArrayList<>();
        for (EarlyWarningDebtListEntity earlyWarningDebtListEntity : earlyWarningDebtListEntityList) {

            BondRiskInformationSheetEntity bondRiskInformationSheetEntity = new BondRiskInformationSheetEntity();
            bondRiskInformationSheetEntity.setVersion(version );//日期
            bondRiskInformationSheetEntity.setBondName(earlyWarningDebtListEntity.getBondName());//债券名称
            bondRiskInformationSheetEntity.setBondCode(earlyWarningDebtListEntity.getBondCode());//债券代码
            bondRiskInformationSheetEntity.setStatus(earlyWarningDebtListEntity.getBondRisk());//状态

            //自营持有债券信息
            List<ProprietaryHoldingBondInformationEntity> proprietaryHoldingBondInformationEntities = proprietaryHoldingBondInformationEntityList.stream().filter(w -> String.valueOf(w.getStockCode()).equals(earlyWarningDebtListEntity.getBondCode())).collect(Collectors.toList());
            ProprietaryHoldingBondInformationEntity proprietaryHoldingBondInformationEntity = new ProprietaryHoldingBondInformationEntity();
            if (proprietaryHoldingBondInformationEntities.size() > 0) {

                proprietaryHoldingBondInformationEntity = proprietaryHoldingBondInformationEntities.get(0);
                //说明有
                if (proprietaryHoldingBondInformationEntity != null){
                    //持仓数量
                    if (proprietaryHoldingBondInformationEntity.getNumberOfBonds() != null) {
                        bondRiskInformationSheetEntity.setPositionTheNumber(proprietaryHoldingBondInformationEntity.getNumberOfBonds());
                    }
                    //上月末自由券数量
                    if (proprietaryHoldingBondInformationEntity.getNumberOfFreeCoupons() != null) {
                        bondRiskInformationSheetEntity.setNumberOfFreeVolumesAtTheEndOfLastMonth(proprietaryHoldingBondInformationEntity.getNumberOfFreeCoupons());
                    }
                    //剩余月份
                    if (proprietaryHoldingBondInformationEntity.getInTheRemaining() != null){
                        bondRiskInformationSheetEntity.setInTheRemaining(proprietaryHoldingBondInformationEntity.getInTheRemaining());
                    }
                    if (proprietaryHoldingBondInformationEntity.getEndInterestDay() != null) {
                        //到期日
                        bondRiskInformationSheetEntity.setEndInterestDay(proprietaryHoldingBondInformationEntity.getEndInterestDay());
                    }
                    //资产类型
                    if (proprietaryHoldingBondInformationEntity.getInvestmentType() != null) {
                        bondRiskInformationSheetEntity.setAssetTypes(proprietaryHoldingBondInformationEntity.getInvestmentType());
                    }
                    //上月末债券评级
                    if (proprietaryHoldingBondInformationEntity.getRate() != null) {
                        bondRiskInformationSheetEntity.setBondRatingAtTheEndOfLastMonth(proprietaryHoldingBondInformationEntity.getRate());
                    }
                    //信用调整（中债隐含评级）
                    if (proprietaryHoldingBondInformationEntity.getImpliedRatingOfBonds() != null) {
                        bondRiskInformationSheetEntity.setCreditAdjustment(proprietaryHoldingBondInformationEntity.getImpliedRatingOfBonds());
                    }
                    //剩余期限
                    if (proprietaryHoldingBondInformationEntity.getInTheRemaining() != null) {
                        bondRiskInformationSheetEntity.setResidualMaturity(proprietaryHoldingBondInformationEntity.getInTheRemaining().compareTo(new BigDecimal(12))>=0?"大于等于1年":"不足1年");
                    }

                }
            }

            //自营估值债券持仓信息
            List<ProprietaryValuationOfBondHoldingsInformationEntity> proprietaryValuationOfBondHoldingsInformationEntities = proprietaryValuationOfBondHoldingsInformationEntityList.stream().filter(w -> String.valueOf(w.getStockCode()).equals(earlyWarningDebtListEntity.getBondCode())).collect(Collectors.toList());
            if (proprietaryValuationOfBondHoldingsInformationEntities.size()>0){
                ProprietaryValuationOfBondHoldingsInformationEntity proprietaryValuationOfBondHoldingsInformationEntity = proprietaryValuationOfBondHoldingsInformationEntities.get(0);
                //上月末账面价值
                if (proprietaryValuationOfBondHoldingsInformationEntity.getFullValue() != null){
                    bondRiskInformationSheetEntity.setBookValueAtTheEndOfLastMonth(proprietaryValuationOfBondHoldingsInformationEntity.getFullValue());
                }
                //减值规模
                if (proprietaryValuationOfBondHoldingsInformationEntity.getAmountOfImpairment() != null) {
                    bondRiskInformationSheetEntity.setImpairmentScale(proprietaryValuationOfBondHoldingsInformationEntity.getAmountOfImpairment());
                }
            }

            /*
                计算字段
             */
            //月末债券评级分类等级
            int rateNum = 0;
            if (bondRiskInformationSheetEntity.getStatus() != null ){
                //月末债券评级分类
                if (proprietaryHoldingBondInformationEntity != null && proprietaryHoldingBondInformationEntity.getRate() != null) {
                    String rate = proprietaryHoldingBondInformationEntity.getRate();
                    /*//信用调整（中债隐含评级）
                    bondRiskInformationSheetEntity.setCreditAdjustment(rate);*/
                    if (rate.equals(SysConstant.AAA) || rate.equals(SysConstant.AAAPLUS)) {
                        bondRiskInformationSheetEntity.setAtTheEndOfTheBondRatingClassification(SysConstant.AAA_LEVEL);
                        rateNum = SysConstant.FIVE;

                    }else if(rate.equals(SysConstant.AAASUB)||rate.equals(SysConstant.AAPLUS)){
                        bondRiskInformationSheetEntity.setAtTheEndOfTheBondRatingClassification(SysConstant.AAA_LEVEL_DOWN);
                        rateNum = SysConstant.FOUR;

                    }else if(rate.equals(SysConstant.AA)||rate.equals(SysConstant.AADOUBLE)){
                        bondRiskInformationSheetEntity.setAtTheEndOfTheBondRatingClassification(SysConstant.AA_PLUS_DOWN);
                        rateNum = SysConstant.THREE;

                    }else if(rate.equals(SysConstant.AASUB)||rate.equals(SysConstant.APLUS)||rate.equals(SysConstant.A)||rate.equals(SysConstant.ASUB)||rate.equals(SysConstant.BBBPLUS)||rate.equals(SysConstant.BBB)){
                        bondRiskInformationSheetEntity.setAtTheEndOfTheBondRatingClassification(SysConstant.AA_LEVEL_DOWN);
                        rateNum = SysConstant.TWO;

                    }else {
                        bondRiskInformationSheetEntity.setAtTheEndOfTheBondRatingClassification(SysConstant.BBB_DPWN);
                        rateNum = SysConstant.ONE;
                    }
                }

            }

            //优质流动性资产
            if (bondRiskInformationSheetEntity.getAtTheEndOfTheBondRatingClassification() != null && (bondRiskInformationSheetEntity.getAtTheEndOfTheBondRatingClassification().equals(SysConstant.AAA_LEVEL)||
                    bondRiskInformationSheetEntity.getAtTheEndOfTheBondRatingClassification().equals(SysConstant.AAA_LEVEL_DOWN)
            )){
                /*
                    公式：(上月末自由券数量/持仓数量)*上月末账面价值
                 */
                //(上月末自由券数量/持仓数量)
                if (bondRiskInformationSheetEntity.getNumberOfFreeVolumesAtTheEndOfLastMonth() != null && bondRiskInformationSheetEntity.getPositionTheNumber() != null) {
                    BigDecimal numberOfFreeVolumesAtTheEndOfLastMonth = bondRiskInformationSheetEntity.getNumberOfFreeVolumesAtTheEndOfLastMonth() ;//上月末自由券数量
                    BigDecimal positionTheNumber = bondRiskInformationSheetEntity.getPositionTheNumber() ;//持仓数量
                    if (positionTheNumber.compareTo(new BigDecimal(0))!=0){
                        BigDecimal divide = numberOfFreeVolumesAtTheEndOfLastMonth.divide(positionTheNumber);
                        if (bondRiskInformationSheetEntity.getBookValueAtTheEndOfLastMonth() != null) {
                            //优质流动性资产
                            bondRiskInformationSheetEntity.setHighQualityLiquidAssets(divide.multiply(bondRiskInformationSheetEntity.getBookValueAtTheEndOfLastMonth()));
                        }
                    }
                }

            }else {
                //优质流动性资产
                bondRiskInformationSheetEntity.setHighQualityLiquidAssets(new BigDecimal(SysConstant.ZERO));
            }
            /*
                信用调整（计算）——
             */
            //信用调整分类等级
            int creditAdjustmentNum = 0;
            //判断是否是低预警 类型(1:违约类PD  2:高预警类PD  3:低预警类PD)
            if (bondRiskInformationSheetEntity.getStatus() != null ){//低预警类
                //信用调整（中债隐含评级）分类
                if (bondRiskInformationSheetEntity.getCreditAdjustment() != null) {
                    String creditAdjustment = bondRiskInformationSheetEntity.getCreditAdjustment();
                    if (creditAdjustment.equals(SysConstant.AAA) || creditAdjustment.equals(SysConstant.AAAPLUS)) {
                        bondRiskInformationSheetEntity.setCreditAdjustmentClassify(SysConstant.AAA_LEVEL);
                        creditAdjustmentNum = SysConstant.FIVE;

                    }else if(creditAdjustment.equals(SysConstant.AAASUB)||creditAdjustment.equals(SysConstant.AAPLUS)){
                        bondRiskInformationSheetEntity.setCreditAdjustmentClassify(SysConstant.AAA_LEVEL_DOWN);
                        creditAdjustmentNum = SysConstant.FOUR;

                    }else if(creditAdjustment.equals(SysConstant.AA)||creditAdjustment.equals(SysConstant.AADOUBLE)){

                        bondRiskInformationSheetEntity.setCreditAdjustmentClassify(SysConstant.AA_PLUS_DOWN);
                        creditAdjustmentNum = SysConstant.THREE;

                    }else if(creditAdjustment.equals(SysConstant.AASUB)||creditAdjustment.equals(SysConstant.APLUS)||creditAdjustment.equals(SysConstant.A)||creditAdjustment.equals(SysConstant.ASUB)||creditAdjustment.equals(SysConstant.BBBPLUS)||creditAdjustment.equals(SysConstant.BBB)){
                        bondRiskInformationSheetEntity.setCreditAdjustmentClassify(SysConstant.AA_LEVEL_DOWN);
                        creditAdjustmentNum = SysConstant.TWO;

                    }else {
                        bondRiskInformationSheetEntity.setCreditAdjustmentClassify(SysConstant.BBB_DPWN);
                        creditAdjustmentNum = SysConstant.ONE;
                    }

                    if (creditAdjustmentNum < rateNum){
                        bondRiskInformationSheetEntity.setWhetherTheCreditRatingIsDowngraded("否");
                    }else {
                        bondRiskInformationSheetEntity.setWhetherTheCreditRatingIsDowngraded("是");
                    }
                }

            }

            /*
                估值调整后规模 公式 上月末账面价值+减值规模
             */
            if (bondRiskInformationSheetEntity.getBookValueAtTheEndOfLastMonth() != null && bondRiskInformationSheetEntity.getImpairmentScale() != null) {
                BigDecimal valuationAdjustedSize = bondRiskInformationSheetEntity.getBookValueAtTheEndOfLastMonth().subtract(bondRiskInformationSheetEntity.getImpairmentScale());
                //估值调整后规模
                bondRiskInformationSheetEntity.setValuationAdjustedSize(valuationAdjustedSize);
            }
            /*
                计算下降等级
             */
            //记录等级的serialNumber
            int serialNumber = -1;
            //获取等级配置list
            //判断预警等级 类型(1:违约类PD  2:高预警类PD  3:低预警类PD)
            List<ConfigEntity> configEntityList =  configService.queryList();
            if (bondRiskInformationSheetEntity.getStatus() != null) {
                if (bondRiskInformationSheetEntity.getStatus() == SysConstant.ONE ) {//违约类
                    List<ConfigEntity> collect = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.THREE).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        ConfigEntity configEntity = collect.get(0);
                        //下降1个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByOneLevels(configEntity.getConfigValue());
                        //下降2个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByTwoLevels(configEntity.getConfigValue());
                        //下降3个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByThreeLevels(configEntity.getConfigValue());
                    }
                } else if (bondRiskInformationSheetEntity.getStatus() == SysConstant.TWO) {//高预警类
                    List<ConfigEntity> collect = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.TWO).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        ConfigEntity configEntity = collect.get(0);
                        //下降1个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByOneLevels(configEntity.getConfigValue());
                        //下降2个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByTwoLevels(configEntity.getConfigValue());
                        //下降3个等级PD
                        bondRiskInformationSheetEntity.setDecreasePdByThreeLevels(configEntity.getConfigValue());
                    }
                } else {
                    List<ConfigEntity> collect = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.ONE).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        List<ConfigEntity> configList = configEntityList.stream().filter(w -> w.getConfigName().equals(bondRiskInformationSheetEntity.getCreditAdjustment())).collect(Collectors.toList());
                        if (configList.size() > 0) {
                            ConfigEntity configEntity = configList.get(0);
                            //获取等级
                            serialNumber = configEntity.getSerialNumber();
                        }
                        if (serialNumber != -1) {//判断非原始等级 -1
                            int addOne = serialNumber+1;
                            List<ConfigEntity> addOneList = collect.stream().filter(w -> w.getSerialNumber() == addOne).collect(Collectors.toList());

                            int addTwo = serialNumber+2;
                            List<ConfigEntity> addTwoList = collect.stream().filter(w -> w.getSerialNumber() == addTwo).collect(Collectors.toList());

                            int addThree = serialNumber+3;
                            List<ConfigEntity> addThreeList = collect.stream().filter(w -> w.getSerialNumber() == addThree).collect(Collectors.toList());

                            if (addOneList.size() > 0) {
                                ConfigEntity configEntity = getConfigEntity(addOneList, SysConstant.AADOUBLE);
                                //下降1个等级PD
                                bondRiskInformationSheetEntity.setDecreasePdByOneLevels(configEntity.getConfigValue());
                                //下降1个等级
                                bondRiskInformationSheetEntity.setDecreasedByOneLevels(configEntity.getConfigName());
                            }

                            if (addTwoList.size() > 0) {
                                ConfigEntity configEntity = getConfigEntity(addTwoList, SysConstant.AADOUBLE);
                                //下降2个等级PD
                                bondRiskInformationSheetEntity.setDecreasePdByTwoLevels(configEntity.getConfigValue());
                                //下降2个等级
                                bondRiskInformationSheetEntity.setDecreasedByTwoLevels(configEntity.getConfigName());
                            }

                            if (addThreeList.size() > 0) {
                                ConfigEntity configEntity = getConfigEntity(addThreeList, SysConstant.AADOUBLE);
                                //下降3个等级PD
                                bondRiskInformationSheetEntity.setDecreasePdByThreeLevels(configEntity.getConfigValue());
                                //下降3个等级
                                bondRiskInformationSheetEntity.setDecreasedByThreeLevels(configEntity.getConfigName());
                            }

                        }
                    }
                }
            }


            List<ConfigEntity> mildCodeList = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.MILD_CODE).collect(Collectors.toList());
            if (mildCodeList.size() > 0) {
                ConfigEntity configEntity = mildCodeList.get(0);
                //估值调整后规模*违约率（轻度） TODO 后续configTypeCode可能会更换
                if ( !StringUtils.isEmpty(configEntity.getConfigValue())) {
                    BigDecimal configValueDel = getBigDecimal(configEntity.getConfigValue());
                    if (bondRiskInformationSheetEntity.getValuationAdjustedSize() != null) {
                        bondRiskInformationSheetEntity.setMild(bondRiskInformationSheetEntity.getValuationAdjustedSize().multiply(configValueDel));
                    }
                }
            }
            List<ConfigEntity> moderateCodeList = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.MODERATE_CODE).collect(Collectors.toList());
            if (moderateCodeList.size() > 0) {
                ConfigEntity configEntity = moderateCodeList.get(0);
                //估值调整后规模*违约率（中度） TODO 后续configTypeCode可能会更换
                if (!StringUtils.isEmpty(configEntity.getConfigValue())) {
                    BigDecimal configValueDel = getBigDecimal(configEntity.getConfigValue());
                    if (bondRiskInformationSheetEntity.getValuationAdjustedSize() != null) {
                        bondRiskInformationSheetEntity.setModerate(bondRiskInformationSheetEntity.getValuationAdjustedSize().multiply(configValueDel));
                    }
                }
            }
            List<ConfigEntity> severeCodeList = configEntityList.stream().filter(w -> w.getConfigTypeCode() == SysConstant.SEVERE_CODE).collect(Collectors.toList());
            if (severeCodeList.size() > 0) {
                ConfigEntity configEntity = severeCodeList.get(0);
                //估值调整后规模*违约率（重度） TODO 后续configTypeCode可能会更换
                if (configEntity.getConfigTypeCode() == SysConstant.SEVERE_CODE && !StringUtils.isEmpty(configEntity.getConfigValue())) {
                    BigDecimal configValueDel = getBigDecimal(configEntity.getConfigValue());
                    if (bondRiskInformationSheetEntity.getValuationAdjustedSize() != null) {
                        bondRiskInformationSheetEntity.setSevere(bondRiskInformationSheetEntity.getValuationAdjustedSize().multiply(configValueDel));
                    }
                }
            }

            bondRiskInformationSheetEntities.add(bondRiskInformationSheetEntity);
        }
//            //删除选中日期的债券风险信息
        deleteDondRiskInformationSheet(version);
        //新增债券风险信息表
        this.saveBatch(bondRiskInformationSheetEntities);
    }

    @Override
    public void doExportByVersion(HttpServletResponse response, QueryParams queryParams) throws IOException {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sh = wb.createSheet();
        /*
            "主键","债券名称","代码","状态","持仓数量","上月末自由卷数量","上月末账面价值","减值规模","剩余月份","到期日","剩余期限","资产类型","上月末债券评级","月末债券评级分类","优质流动性资产","信用调整（中债隐含评级）","信用调整（中债隐含评级）分类","信用评级是否降档","下降1个等级","下降2个等级","下降3个等级","下降1个等级PD","下降2个等级PD","下降3个等级PD","估值调整后规模","估值调整后规模*违约率（轻度）","估值调整后规模*违约率（中度）","估值调整后规模*违约率（重度）","版本日期"
            */
        String[] titles = {"主键","债券名称","代码","状态","持仓数量","上月末自由卷数量","上月末账面价值","减值规模","剩余月份","到期日","剩余期限","资产类型","上月末债券评级","月末债券评级分类","优质流动性资产","信用调整（中债隐含评级）","信用调整（中债隐含评级）分类","信用评级是否降档","下降1个等级","下降2个等级","下降3个等级","下降1个等级PD","下降2个等级PD","下降3个等级PD","估值调整后规模","估值调整后规模*违约率（轻度）","估值调整后规模*违约率（中度）","估值调整后规模*违约率（重度）","版本日期"};
        Row row = sh.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);

        // 第一行设置标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
            cell1.setCellStyle(style);
            //设置单元格大小
            sh.setColumnWidth(i, 6000);
        }
        if (queryParams.getInitDate().contains("-")){
            queryParams.setVersion(Long.valueOf(queryParams.getInitDate().replace("-","")));
        }
        IPage<BondRiskInformationSheetEntity> page = new Page<>();
        page.setCurrent(queryParams.getPageNum());
        page.setSize(queryParams.getPageSize());
        QueryWrapper<BondRiskInformationSheetEntity> wrapper = new QueryWrapper<BondRiskInformationSheetEntity>();
        wrapper.lambda().eq(!StringUtils.isEmpty(queryParams.getVersion()),BondRiskInformationSheetEntity::getVersion, queryParams.getVersion()).orderByDesc(BondRiskInformationSheetEntity::getVersion);
        List<BondRiskInformationSheetEntity> bondRiskInformationSheetEntities = bondRiskInformationSheetDao.selectList(wrapper);
        final String fileName = "自营估值债券持仓信息_%s.xlsx";
        ServletOutputStream outputStream = ResponseUtils.getOutputStreamAndSettingFileFormat(response, fileName);
        //如果该版本得风险因子回溯有数据则填充进Excel
        if (!CollectionUtils.isEmpty(bondRiskInformationSheetEntities)) {
            Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(), BondRiskInformationSheetEntity.class, bondRiskInformationSheetEntities);
            sheets.write(outputStream);
            outputStream.close();
            sheets.close();
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }

    /**
     * 需求 ： 配置等级 AA 与 AA(2)为同级
     *   思路： AA 与 AA(2)的顺序是一样的，如果相同的等级是AA(2) 则取另一个list
     *
     * @param configEntityList
     * @param AA_2
     * @return
     */
    public ConfigEntity getConfigEntity(List<ConfigEntity> configEntityList, String AA_2) {
        ConfigEntity configEntity = configEntityList.get(0);
        if (configEntity.getConfigName().equals(AA_2)){
            configEntity = configEntityList.get(1);
        }
        return configEntity;
    }

    /**
     * 根据版本日期 删除债券风险信息表
     * @param version
     *
     */
    @Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED)
    public void deleteDondRiskInformationSheet(Long version) {
        QueryWrapper<BondRiskInformationSheetEntity> wrapper = new QueryWrapper<BondRiskInformationSheetEntity>();

        wrapper.eq("version", version);
        bondRiskInformationSheetDao.delete(wrapper);
    }

    /**
     * 新增债券风险信息表
     * @param bondRiskInformationSheetEntity
     */
    @Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED)
    public void insertBondRiskInformationSheet(BondRiskInformationSheetEntity bondRiskInformationSheetEntity) {
        //删除选中日期的债券风险信息
        deleteDondRiskInformationSheet(bondRiskInformationSheetEntity.getVersion());
        bondRiskInformationSheetDao.insert(bondRiskInformationSheetEntity);
    }

    /**
     * 将百分比字符串转换为数值 例： “10%” --》 0.10
     * @param configValue
     * @return
     */
    @NotNull
    private BigDecimal getBigDecimal(String configValue) {
        configValue = configValue.substring(0, configValue.length()-1);
        BigDecimal configValueDel = new BigDecimal(configValue).divide(new BigDecimal(100));
        return configValueDel;
    }
}